package com.unitd.base.module.api.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.unitd.base.frame.plugin.module.dto.ResponseUtils;
import com.unitd.base.module.api.entity.BuyGoodsVo;
import com.unitd.base.module.comm.cache.J2CacheUtils;
import com.unitd.base.module.consumer.comm.annotation.LoginUser;
import com.unitd.base.module.consumer.comm.controller.ApiBaseAction;
import com.unitd.base.module.master.pojo.dto.CompanyUserVO;
import com.unitd.base.module.master.pojo.dto.UserVO;
import com.unitd.base.module.master.service.CompanyUserService;
import com.unitd.base.module.shoe.pojo.dto.GoodsVO;
import com.unitd.base.module.shoe.pojo.po.CustomerOrderItemPO;
import com.unitd.base.module.shoe.pojo.po.CustomerOrderPO;
import com.unitd.base.module.shoe.service.GoodsService;
import com.unitd.base.module.shoe.service.OrderItemService;
import com.unitd.base.module.shoe.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lipengjun
 * @email 939961241@qq.com
 * @gitee https://gitee.com/fuyang_lipengjun/platform
 */
@Api(tags = "商品购买")
@RestController
@RequestMapping("/api/buy")
public class ApiBuyController extends ApiBaseAction {

    @Autowired
    private OrderService orderService;
    @Autowired
    private CompanyUserService companyUserService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderItemService orderItemService;

    @ApiOperation(value = "商品添加")
    @PostMapping("/add")
    public Object addBuy(@LoginUser UserVO loginUser) {
        JSONObject jsonParam = getJsonRequest();
        String goodsId = jsonParam.getString("goodsId");
        String listData = jsonParam.getString("listData");
        listData=listData.replaceAll("请配码","11111");

        CustomerOrderPO customerOrderPO = this.createCustomerOrderPO(loginUser);
        orderService.insertCustomerOrderPO(customerOrderPO);
        Map param  = Maps.newHashMap();
        param.put("F1927",customerOrderPO.getF1927());
        List<CustomerOrderPO> list = orderService.selectByBean(param);//重新从数据库获取对象，得到id值
        if(list!=null&&!list.isEmpty()){
            customerOrderPO = list.get(0);
        }

        List<CustomerOrderItemPO> customerOrderItemPOList = this.createCustomerOrderItemPOs(loginUser,customerOrderPO,goodsId,listData);

        if(customerOrderItemPOList!=null&&!customerOrderItemPOList.isEmpty()){
            customerOrderItemPOList.forEach(e->{
                orderItemService.insert(e);
            });
        }

        Map<String, Object> resultObj = new HashMap();
        resultObj.put("orderNo",customerOrderPO.getF1927());

        return ResponseUtils.toResponsSuccess(resultObj);
    }

    private List<CustomerOrderItemPO> createCustomerOrderItemPOs(UserVO loginUser,CustomerOrderPO customerOrderPO,String goodsId,String listData){

        List<CustomerOrderItemPO> customerOrderItemPOList = Lists.newArrayList();

        List<Map<String,String>> reqOrderList = (List<Map<String, String>>) JSON.parse(listData);
        int num = 0;
        for(Map<String,String> orderMapInfo :reqOrderList) {

            Map<String, Object> param = Maps.newHashMap();
            param.put("F3125", orderMapInfo.get("code"));//产品编号
            List<GoodsVO> newGoods = goodsService.selectByBean(getUserDefDbName(), param);
            GoodsVO goodsVO = newGoods.get(0);

            CustomerOrderItemPO customerOrderItemPO = new CustomerOrderItemPO();
            //            字段名	说明	字段类型
            //            ID		整数	id用于与主表 ID对应
            customerOrderItemPO.setId(customerOrderPO.getId());
            //            iord	行标	整数	用1 2 3整数递增
            customerOrderItemPO.setIord(++num);
            //            F1935	货号	字符50
            customerOrderItemPO.setF1935(goodsId);
            //            F1936	颜色	字符50
            customerOrderItemPO.setF1936(goodsVO.getF3128_color());
            //            F1937	件数	小数2	必填
            customerOrderItemPO.setF1937(BigDecimal.valueOf(Double.valueOf((String) (orderMapInfo.get("boxCount")))));
            //            F1939	单价	小数2

            if (goodsVO != null) {
                customerOrderItemPO.setF1939(goodsVO.getF3131_price());
            }
            //            F1947	产品编号	字符50
            customerOrderItemPO.setF1947(goodsId);
            //            F2116	码段	字符50
            customerOrderItemPO.setF2116(goodsVO.getF3129_size());
            //            F12694	配码	字符50
            customerOrderItemPO.setF12694("");//配码默认空
            //            F12785	产品编号+配码	字符100
            customerOrderItemPO.setF12785(customerOrderItemPO.getF1947() + customerOrderItemPO.getF12694());
            //            F1938	双/箱	小数2
            customerOrderItemPO.setF1938(goodsVO.getF3130_box());
            //            F2107	双数	小数2
            customerOrderItemPO.setF2107(customerOrderItemPO.getF1938().multiply(customerOrderItemPO.getF1937()));
            //            F1940	金额	小数2
            customerOrderItemPO.setF1940(goodsVO.getF3131_price().multiply(customerOrderItemPO.getF2107()));

            customerOrderItemPOList.add(customerOrderItemPO);
        }
        return customerOrderItemPOList;
    }

    private  CustomerOrderPO createCustomerOrderPO(UserVO loginUser){
        CustomerOrderPO customerOrderPO =  new CustomerOrderPO();
//        字段名	说明	字段类型
//        ID		整数
//        iord	行标	整数  	1
        customerOrderPO.setIord(1);
//        FillDate	填报日期	日期时间	自动获取当前日期时间
        Date curDate = new Date(System.currentTimeMillis());
        customerOrderPO.setFilldate(curDate);
//        ModifyDate	修改时间	日期时间	自动获取当前日期时间
        customerOrderPO.setModifydate(curDate);
//        RepID		整数	169
        customerOrderPO.setRepid(169);
//        DeptID		整数	0
        customerOrderPO.setDeptid(0);
//        OperID	填写人员ID	整数	61
        customerOrderPO.setOperid(61);
//        bIsFinish		整数	1
        customerOrderPO.setBisfinish("1");
//        bLocked	锁定	整数	1
        customerOrderPO.setBlocked("1");
//        bCanViewWhenNofinished		整数	0
        customerOrderPO.setBcanviewwhennofinished("0");
//        OPerID2	修改人员ID	整数	61
        customerOrderPO.setOperid2(61);
//        F1927	订单号	字符50 唯一
        String uuid = UUID.randomUUID().toString();	//获取UUID并转化为String对象
        uuid = uuid.replace("-", "");
        String strDateFormat = "yyyyMMdd";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String dataStr = sdf.format(curDate);
        customerOrderPO.setF1927("XCX"+dataStr+uuid);
//        F1928	客户名称	字符100	必填
        CompanyUserVO companyUserVO =companyUserService.selectByMobile(loginUser.getMobile());
        if(companyUserVO.getUserLevelId().intValue()!=4){
            companyUserVO = companyUserService.selectByCompanyIdAndUserId(companyUserVO.getCompanyId(),companyUserVO.getProxyUserId());
        }
        customerOrderPO.setF1928(companyUserVO.getNickName());
//        F1929	订单日期	日期	必填
        customerOrderPO.setF1929(curDate);
//        F1930	制单人	字符100	小程序用户
        customerOrderPO.setF1930("小程序用户");
//        F2911	审核	字符100	自动获取审核用户账户
        customerOrderPO.setF2911("");
//        F1931	制单日期	日期
        customerOrderPO.setF1931(curDate);
//        F1952	客户编号	字符50
        customerOrderPO.setF1952(companyUserVO.getUserNo());
//        F2847	订单来源	字符50	自动电脑端，小程序
        customerOrderPO.setF2847("小程序");

        return  customerOrderPO;
    }
}
